import io
import json
import oss2

class OssHandler:
    def __init__(self, access_key, secret_key, bucket_name, endpoint):
        self.auth = oss2.Auth(access_key, secret_key)
        self.bucket = oss2.Bucket(self.auth, endpoint, bucket_name)

    def upload_file(self, file, oss_key):
        try:
            result = self.bucket.put_object(oss_key, file)
            if result.status == 200:
                print(f"Uploaded file to OSS with key {oss_key} successfully.")
                return True
            else:
                print(f"Failed to upload file to OSS with key {oss_key}.")
                return False
        except Exception as e:
            print(f"Error uploading to OSS: {e}")
            return False
    def upload_json(self, json_data, oss_key):
        try:
            self.bucket.put_object(oss_key, json.dumps(json_data))
            print(f"✅ JSON 数据已上传到 OSS: {oss_key}")
        except Exception as e:
            print(f"❌ 上传失败: {e}")
    def download_file(self, oss_key, local_file):
        try:
            result = self.bucket.get_object_to_file(oss_key, local_file)
            if result.status == 200:
                print(f"Downloaded {oss_key} from OSS to {local_file} successfully.")
                return True
            else:
                print(f"Failed to download {oss_key} from OSS to {local_file}.")
                return False
        except Exception as e:
            print(f"Error downloading from OSS: {e}")
            return False
    def download_file_stream(self, oss_key: str) -> io.BytesIO:
        try:
            result = self.bucket.get_object(oss_key)
            if result.status == 200:
                print(f"Downloaded {oss_key} from OSS successfully (to memory).")
                return io.BytesIO(result.read())
            else:
                raise Exception(f"Failed to download {oss_key}, status: {result.status}")
        except Exception as e:
            print(f"Error downloading from OSS: {e}")
            raise